package com.example.app.ui.Discover;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import com.example.app.R;
import java.util.List;
public class DiscoverAdapter extends BaseAdapter {
    private Context context;
    private List<Post> postList;
    public DiscoverAdapter(Context context, List<Post> postList) {
        this.context = context;
        this.postList = postList;
    }
    @Override
    public int getCount() { return postList.size(); }
    @Override
    public Object getItem(int position) { return postList.get(position); }
    @Override
    public long getItemId(int position) { return position; }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.discover, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Post post = postList.get(position);
        bindPostData(holder, post, position);
        return convertView;
    }
    private void bindPostData(ViewHolder holder, Post post, int position) {
        holder.avatar.setImageResource(post.avatarRes);
        holder.author.setText(post.author);
        holder.content.setText(post.content);
        holder.time.setText(post.time);
        if (post.imageRes != 0) {
            holder.image.setImageResource(post.imageRes);
            holder.image.setVisibility(View.VISIBLE);
        } else {
            holder.image.setVisibility(View.GONE);
        }
        updateLikeUI(holder, post);
        holder.btnLike.setOnClickListener(v -> toggleLike(post, holder));
        holder.btnComment.setOnClickListener(v -> showCommentDialog(post, null));
        holder.btnMore.setOnClickListener(v -> showPostMenu(holder.btnMore, post));
        bindComments(holder.commentsLayout, post.comments, post);
    }
    private void updateLikeUI(ViewHolder holder, Post post) {
        SharedPreferences sp = context.getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
        String currentUser = sp.getString("username", "用户");
        boolean isLiked = post.likes.contains(currentUser);
        holder.btnLike.setCompoundDrawablesWithIntrinsicBounds(
                isLiked ? R.drawable.tx : R.drawable.ic_like,
                0, 0, 0
        );
        holder.btnLike.setTextColor(isLiked ?
                ContextCompat.getColor(context, R.color.white) :
                ContextCompat.getColor(context, R.color.purple_700));
        String likeText = post.likes.isEmpty() ? "赞" :
                post.likes.size() + (post.likes.size() > 1 ? "人赞过" : "人赞");
        holder.btnLike.setText(likeText);
    }
    private void toggleLike(Post post, ViewHolder holder) {
        SharedPreferences sp = context.getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
        String currentUser = sp.getString("username", "用户");
        if (post.likes.contains(currentUser)) {
            post.likes.remove(currentUser);
        } else {
            post.likes.add(currentUser);
        }
        updateLikeUI(holder, post);
    }
    private void bindComments(LinearLayout layout, List<Comment> comments, Post post) {
        layout.removeAllViews();
        for (Comment comment : comments) {
            View commentView = LayoutInflater.from(context)
                    .inflate(R.layout.item_comment, layout, false);

            TextView tvAuthor = commentView.findViewById(R.id.tv_author);
            TextView tvContent = commentView.findViewById(R.id.tv_content);
            String content = comment.targetUser != null ?
                    "回复 " + comment.targetUser + ": " + comment.content :
                    comment.content;
            tvAuthor.setText(comment.author + ":");
            tvContent.setText(content);
            tvAuthor.setOnClickListener(v -> {
                Toast.makeText(context, "跳转到" + comment.author + "的主页", Toast.LENGTH_SHORT).show();
            });
            tvContent.setOnClickListener(v -> {
                showCommentDialog(post, comment.author);
            });
            layout.addView(commentView);
        }
    }
    private void showPostMenu(View anchor, Post post) {
        PopupMenu popup = new PopupMenu(context, anchor);
        popup.getMenu().add("评论");
        popup.getMenu().add("点赞");
        popup.setOnMenuItemClickListener(item -> {
            if (item.getTitle().equals("点赞")) {
                toggleLike(post, null);
                return true;
            }
            if (item.getTitle().equals("评论")) {
                showCommentDialog(post, null);
                return true;
            }
            return false;
        });
        popup.show();
    }
    private void showCommentDialog(Post post, String targetUser) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(targetUser == null ? "发表评论" : "回复 " + targetUser);
        final EditText input = new EditText(context);
        if (targetUser != null) {
            input.setHint("回复 " + targetUser);
        }
        builder.setView(input);
        builder.setPositiveButton("发送", (dialog, which) -> {
            String content = input.getText().toString().trim();
            if (!content.isEmpty()) {
                SharedPreferences sp = context.getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
                String username = sp.getString("username", "用户");

                Comment comment = new Comment(username, targetUser, content);
                post.comments.add(comment);
                notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    static class ViewHolder {
        ImageView avatar;
        TextView author;
        TextView content;
        ImageView image;
        TextView time;
        LinearLayout commentsLayout;
        TextView btnLike;
        TextView btnComment;
        ImageButton btnMore;
        public ViewHolder(View view) {
            avatar = view.findViewById(R.id.image_avatar);
            author = view.findViewById(R.id.text_author);
            content = view.findViewById(R.id.text_content);
            image = view.findViewById(R.id.image_post);
            time = view.findViewById(R.id.text_time);
            commentsLayout = view.findViewById(R.id.layout_comments);
            btnLike = view.findViewById(R.id.btn_like);
            btnComment = view.findViewById(R.id.btn_comment);
            btnMore = view.findViewById(R.id.btn_more);
        }
    }
}